package org.dragonnova.business.web;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.dragonnova.business.common.Constants;
import org.dragonnova.business.dto.DeviceTagDto;
import org.dragonnova.business.dto.PageDto;
import org.dragonnova.business.dto.TagValueDto;
import org.dragonnova.business.model.DeviceBox;
import org.dragonnova.business.model.DeviceTag;
import org.dragonnova.business.model.DeviceTag.Second;
import org.dragonnova.business.model.TagReports;
import org.dragonnova.business.model.TagValue;
import org.dragonnova.business.model.User;
import org.dragonnova.business.service.TagService;
import org.dragonnova.business.service.UserService;
import org.dragonnova.business.util.IOTBeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.base.pub.util.Base64Util;
import com.base.pub.util.DateUtils;
import com.base.pub.util.TokenUtils;

@Controller
@RequestMapping("/tag")
public class TagController extends BaseController {
	@Autowired
	private TagService tagService;
	@Autowired
	private UserService userService;

	/**
	 * 删除
	 * 
	 * @param session
	 * @param id
	 *            设备编号
	 * @return
	 */
	@RequestMapping("/delTag")
	@ResponseBody
	public Map<String, Object> delTag(HttpSession session,
			@RequestParam(value = "id") String id) {
		Integer uId = getUserId(session, true);
		id = Base64Util.getFromBase64(id);
		try {
			List<DeviceTag> list = tagService.findDeviceTag(uId, null, id, 1);
			if (tagService.delTagById(id)) {
				tagService.delValueAndThresoldByTagSn(list.get(0).getSn());
				return packDelInfo(true);
			} else {
				return packDelInfo(false);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return warnException(e);
		}
	}

	/**
	 * 获取标签报表，标签历史统计
	 * 
	 * @param type
	 * @param session
	 * @param sn
	 * @param timeType
	 *            年，季，月，日，时
	 * @return
	 */
	@RequestMapping("/getReport")
	@ResponseBody
	public Map<String, Object> getReport(
			HttpSession session,
			@RequestParam(value = "tagId", required = true) String tagId,
			@RequestParam(value = "type", required = true) Integer type, // 1按固定最近天数查询，2按时间段查询
			@RequestParam(value = "startTime", required = false) String startTime,
			@RequestParam(value = "endTime", required = true) String endTime,
			@RequestParam(value = "days", required = false) Integer days) {
		Integer uId = getUserId(session, true);
		try {
			TagReports tr = tagService.getReport(uId,
					Base64Util.getFromBase64(tagId), startTime, endTime, days,
					type);
			return packData(tr);
		} catch (Exception e) {
			e.printStackTrace();
			return warnException(e);
		}
	}
	
	/**
	 * 保存tag
	 * 
	 * @param session
	 * @param password
	 * @return
	 */
	@RequestMapping("/addDeviceTag")
	@ResponseBody
	public Map<String, Object> addTag(HttpSession session,
			@Validated(Second.class) DeviceTag deviceTag, String password,
			BindingResult result) {
		if (result.hasErrors()) {
			return bindingResult(result);
		}
		Integer uId = getUserId(session, false);
		deviceTag.setCreatorUid(uId);
		deviceTag.setSign("1");
		try {
			DeviceTag tag = tagService.findDeviceTagBySn(deviceTag.getSn());
			if (tag != null) {
				return packInfo(false, "设备编号已存在！保存");
			}
			return packSaveInfo(tagService.addDeviceTag(deviceTag));
		} catch (Exception e) {
			e.printStackTrace();
			return warnException(e);
		}
	}

	/**
	 * 修改tag
	 * 
	 * @param session
	 * @param password
	 * @return
	 */
	@RequestMapping("/updateDeviceTag")
	@ResponseBody
	public Map<String, Object> updateTag(HttpSession session,
			@Validated DeviceTag deviceTag, String password,
			BindingResult result) {
		deviceTag.setUpdatetime(DateUtils.getTimes(new Date(),
				"yyyy-MM-dd HH:mm:ss"));
		String id = deviceTag.getId();
		deviceTag.setIdFromBase64(id);
		try {
			return packSaveInfo(tagService.updateDeviceTag(deviceTag));
		} catch (Exception e) {
			e.printStackTrace();
			return warnException(e);
		}
	}

	/**
	 * @param title
	 * @param sn
	 * @param orderType
	 *            为 1时上报时间降序，2.上报时间升序，3.区域升序，4.区域降序
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/findDeviceTag")
	public String findDeviceTag(HttpSession session,
			@RequestParam(value="id",required=true)String id, 
			@RequestParam(value="searchText",required=false)String searchText,
			@RequestParam(value="orderType",required=false)Integer orderType, 
			@RequestParam(value="callback",required=false)String callback, Model model) {
		Integer userId = getUserId(session, true);
		List<DeviceTag> list = new ArrayList<DeviceTag>();
		try {
			list = tagService.findDeviceTag(userId, searchText,
					Base64Util.getFromBase64(id), orderType);
			if (list.size() < 1) {
				return Constants.THYMELEAF_TEMPLATE_EMPTY;
			}
			// DeviceTagDto tagDto = new DeviceTagDto();
			// IOTBeanUtils.copyPropertiesIgnoreNull(list.get(0),tagDto);
			// model.addAttribute("data", packData(tagDto));
			model.addAttribute("data", packData(list.get(0)));
			return callback;
		} catch (Exception e) {
			e.printStackTrace();
			return Constants.THYMELEAF_TEMPLATE_ERROR;
		}
	}
	
	/**
	 * @param title
	 * @param sn
	 * @param orderType
	 *            为 1时上报时间降序，2.上报时间升序，3.区域升序，4.区域降序
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/findDeviceTagJson")
	@ResponseBody
	public Map<String, Object> findDeviceTag(HttpSession session,
			@RequestParam(value = "id",required = false)String id,
			@RequestParam(value="searchText",required = false)String searchText, 
			@RequestParam(value="orderType",required = false)Integer orderType) {
		Integer userId = getUserId(session, true);
		List<DeviceTag> list = new ArrayList<DeviceTag>();
		try {
			list = tagService.findDeviceTag(userId, searchText,
					Base64Util.getFromBase64(id), orderType);
			return packData(list);
		} catch (Exception e) {
			e.printStackTrace();
			return warnException(e);
		}
	}

	/**
	 * 查询最新devicebox
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/findDeviceBox")
	public String findDeviceBox(HttpServletRequest request,
			@RequestParam(value="id",required=false)String id, 
			@RequestParam(value="searchText",required=false)String searchText,
			@RequestParam(value="callback",required=false)String callback,
			Model model) {

		try {
			String token = TokenUtils.getToken(request);
			if (StringUtils.isEmpty(token)) {
				model.addAttribute("data", "token 过期");
				return Constants.THYMELEAF_TEMPLATE_LOGIN;
			}

			String userName = TokenUtils.getValue(token, "userName");
			if (StringUtils.isEmpty(userName)) {
				model.addAttribute("data", "用户不存在");
				return Constants.THYMELEAF_TEMPLATE_LOGIN;
			}

			User user = userService.getUserByName(userName);
			List<DeviceBox> list = tagService.findDeviceBox(user.getId(),
					searchText, Base64Util.getFromBase64(id));
			model.addAttribute("data", packData(list));
			return callback;
		} catch (Exception e) {
			e.printStackTrace();
			return Constants.THYMELEAF_TEMPLATE_ERROR;
		}
	}

	/**
	 * 查询最新devicebox
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/findDeviceBoxJson")
	@ResponseBody
	public Map<String, Object> findDeviceBox(HttpServletRequest request,
			@RequestParam(value = "searchText",required = false)String searchText,
			@RequestParam(value = "id",required = false)String id) {

		try {
			String token = TokenUtils.getToken(request);
			if (StringUtils.isEmpty(token)) {
				return packInfo(false, "用户不存在，请登陆。");
			}

			String userName = TokenUtils.getValue(token, "userName");
			if (StringUtils.isEmpty(userName)) {
				return packInfo(false, "token已过期。");
			}

			User user = userService.getUserByName(userName);
			List<DeviceBox> list = tagService.findDeviceBox(user.getId(),
					searchText, Base64Util.getFromBase64(id));
			return packData(list);
		} catch (Exception e) {
			e.printStackTrace();
			return warnException(e);
		}
	}

	/**
	 * 保存tag value
	 * 
	 * @param session
	 * @param password
	 * @return
	 */
	@RequestMapping("/addTagValue")
	@ResponseBody
	public Map<String, Object> addTagValue(HttpSession session,
			TagValue deviceValue, String password) {
		try {
			return packSaveInfo(tagService.addTagValue(deviceValue));
		} catch (Exception e) {
			e.printStackTrace();
			return warnException(e);
		}
	}

	/**
	 * 保存tag value
	 * 
	 * @param session
	 * @param password
	 * @return
	 */
	@RequestMapping("/addTest")
	@ResponseBody
	public String addTestData(
			@RequestParam(value = "sn", required = true) String sn,
			@RequestParam(value = "mon", required = true) String mon) {
		for (int i = 1; i <= 31; i++) {
			TagValue tagValue = new TagValue();
			tagValue.setTagSn(sn);
			tagValue.setStatus(1);
			tagValue.setSign("0");
			for (int j = 0; j < 24; j++) {
				tagValue.setHum(23f + (j * i) % 20);
				tagValue.setTemp(25f + (j * i) % 20);
				tagValue.setBattery(69f + (j * i) % 20);
				tagValue.setInserttime("2017-" + mon + "-" + i + " " + j
						+ ":11:00");
				tagValue.setUpdatetime("2017-" + mon + "-" + i + " " + j
						+ ":11:00");
				try {
					tagService.addTagValue(tagValue);
				} catch (Exception e) {
					e.printStackTrace();
					return "失败" + e.getMessage();
				}
			}
		}
		return "success";
	}

	/**
	 * 修改路由信息-绑定路由用户
	 */
	@RequestMapping("/updateBox")
	@ResponseBody
	public Map<String, Object> updateBox(HttpSession session, DeviceBox box) {
		try {
			box.setUpdatetime(DateUtils.getTimes(new Date(),
					"yyyy-MM-dd hh:mm:ss"));
			return packSaveInfo(tagService.updateBox(box));
		} catch (Exception e) {
			e.printStackTrace();
			return warnException(e);
		}
	}

	/**
	 * 
	 * @param session
	 * @param indexPage
	 * @param orderType
	 * @return
	 */
//	@RequestMapping(value = "/findTagByPage/{indexPage}/{pageSize}/{orderType}/{searchText}" ,method=RequestMethod.GET)
//	public String findTagByPage(HttpSession session,Model model,
//			@PathVariable(value = "indexPage") Integer indexPage,
//			@PathVariable(value = "pageSize")Integer pageSize,
//			@PathVariable(value = "orderType")Integer orderType, 
//			@PathVariable(value = "searchText")String searchText) {
	@RequestMapping(value = "/findTagByPage" ,method=RequestMethod.POST)
	public String findTagByPage(HttpSession session,Model model,PageDto<List<DeviceTagDto>> page,@RequestParam("callback") String callback
			) {
		 Integer userId = getUserId(session,true);
//		Integer userId = -10;
		try {
			PageDto<List<DeviceTag>> source = tagService.findTagByPage(userId,
					page.getIndexPage(), page.getPageSize(), page.getOrderType(), page.getSearchText());
			if (source.getList().size() < 1) {
				model.addAttribute("data", "查询结果为空");
				return Constants.THYMELEAF_TEMPLATE_EMPTY;
			}
			page.setList(new ArrayList<DeviceTagDto>());
			page.setTotalCount(source.getTotalCount());
			for (DeviceTag tag : source.getList()) {
				DeviceTagDto tagDto = new DeviceTagDto();
				if (tag.getTagValue() != null) {
					TagValueDto valueDto = new TagValueDto();
					IOTBeanUtils.copyPropertiesIgnoreNull(tag.getTagValue(),
							valueDto);
					tagDto.setTagValue(valueDto);
				}
				IOTBeanUtils.copyPropertiesIgnoreNull(tag, tagDto);
				page.getList().add(tagDto);
			}
			model.addAttribute("data", packData(page));
			return callback;
		} catch (Exception e) {
			e.printStackTrace();
			return Constants.THYMELEAF_TEMPLATE_ERROR;
		}
	}
}
